/* eslint no-unused-vars:0 */
import React from 'react';
import {
    Table,
    Divider,
    Input,
    Button,
    Icon,
    Tag,
    message,
    Popconfirm
} from 'antd';
import Highlighter from 'react-highlight-words';
import './listTab.css';

class listTab extends React.Component {
    state = {
        searchText: '',
        userList: [],
        iconLoading: false
    };

    componentDidMount() {
        this.getUserInfo();
    }

    // 刷新
    refresh = () => {
        this.setState({ iconLoading: true });
        this.getUserInfo();
    };

    // 获取用户列表
    getUserInfo = () => {
        this.$post('/user/findAll')
            .then((res) => {
                this.setState({ userList: res });
                this.setState({ iconLoading: false });
            })
            .catch((error) => {
                console.log(error);
            });
    };

    // 初始化用户密码
    handleInitial = (user, record) => {
        this.$post('/user/initial', { id: user.id }).then((res) => {
            if (res.msg === 'success') message.success('初始化成功');
            this.getUserInfo();
        });
    };

    // 状态修改
    handleStatus = (user, record) => {
        this.$post('/user/updateStatus', { id: user.id }).then((res) => {
            if (res.msg === 'success') message.success('修改成功');
            this.getUserInfo();
        });
    };

    // 删除用户
    handleDelete = (user, record) => {
        if (user.status === '0') {
            message.error('注销用户无法删除');
        } else {
            this.$post('/user/deleteById', { id: user.id })
                .then((res) => {
                    if (res.msg === 'success') {
                        message.success('删除成功');
                        this.getUserInfo();
                    } else message.error('删除失败');
                })
                .catch((error) => {
                    console.log(error);
                });
        }
    };

    // 搜索框
    getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({
            setSelectedKeys,
            selectedKeys,
            confirm,
            clearFilters
        }) => (
            <div style={{ padding: 8 }}>
                <Input
                    ref={(node) => {
                        this.searchInput = node;
                    }}
                    value={selectedKeys[0]}
                    onChange={(e) =>
                        setSelectedKeys(e.target.value ? [e.target.value] : [])
                    }
                    onPressEnter={() =>
                        this.handleSearch(selectedKeys, confirm)
                    }
                    style={{ width: 188, marginBottom: 8, display: 'block' }}
                />
                <Button
                    type="primary"
                    onClick={() => this.handleSearch(selectedKeys, confirm)}
                    icon="search"
                    size="small"
                    style={{ width: 90, marginRight: 8 }}>
                    搜索
                </Button>
                <Button
                    onClick={() => this.handleReset(clearFilters)}
                    size="small"
                    style={{ width: 90 }}>
                    重置
                </Button>
            </div>
        ),
        filterIcon: (filtered) => (
            <Icon
                type="search"
                style={{ color: filtered ? '#1890ff' : undefined }}
            />
        ),
        onFilter: (value, record) =>
            record[dataIndex]
                .toString()
                .toLowerCase()
                .includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
                setTimeout(() => this.searchInput.select());
            }
        },
        render: (text) => (
            <Highlighter
                highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                searchWords={[this.state.searchText]}
                autoEscape
                textToHighlight={text.toString()}
            />
        )
    });

    // 搜索框中的确认按钮
    handleSearch = (selectedKeys, confirm) => {
        confirm();
        this.setState({ searchText: selectedKeys[0] });
    };

    // 搜索框中的重置按钮
    handleReset = (clearFilters) => {
        clearFilters();
        this.setState({ searchText: '' });
    };

    render() {
        const columns = [
            {
                title: '用户名',
                dataIndex: 'username',
                key: 'username',
                width: '10%',
                ...this.getColumnSearchProps('username')
            },
            {
                title: '类型',
                dataIndex: 'role',
                key: 'role',
                width: '7%',
                ...this.getColumnSearchProps('role'),
                render: (role) => {
                    let color = 'geekblue';
                    if (role === 'admin' || role === 'root') {
                        color = 'volcano';
                    }
                    return (
                        <span>
                            <Tag color={color} key={role}>
                                {role.toUpperCase()}
                            </Tag>
                        </span>
                    );
                }
            },
            {
                title: '性别',
                dataIndex: 'sex',
                key: 'sex',
                width: '8%',
                ...this.getColumnSearchProps('sex')
            },
            {
                title: '学校',
                dataIndex: 'college',
                key: 'college',
                width: '12%',
                ...this.getColumnSearchProps('college')
            },
            {
                title: '联系方式',
                dataIndex: 'contact',
                key: 'contact',
                width: '15%'
            },
            {
                title: '邮箱',
                dataIndex: 'mail',
                key: 'mail',
                width: '20%'
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                width: '10%',
                ...this.getColumnSearchProps('status'),
                render: (status) => {
                    let color = '';
                    if (status === '1') {
                        status = '激活';
                        color = 'volcano';
                    } else {
                        status = '注销';
                    }
                    return (
                        <Tag color={color} key={status}>
                            {status.toUpperCase()}
                        </Tag>
                    );
                }
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => {
                    return (
                        <span>
                            <a onClick={() => this.handleStatus(text, record)}>
                                {record.status === '1' ? '注销' : '激活'}
                            </a>
                            <Divider type="vertical" />
                            <a onClick={() => this.handleInitial(text, record)}>
                                初始化
                            </a>
                            <Divider type="vertical" />
                            <Popconfirm
                                title="确认删除用户及其相关信息？"
                                onConfirm={() =>
                                    this.handleDelete(text, record)
                                }
                                okText="确认"
                                cancelText="取消">
                                <a href="#">删除</a>
                            </Popconfirm>
                        </span>
                    );
                }
            }
        ];
        return (
            <div>
                <Button
                    style={{
                        marginTop: '20px',
                        marginBottom: '20px',
                        marginLeft: '0px'
                    }}
                    type="primary"
                    icon="reload"
                    loading={this.state.iconLoading}
                    onClick={this.refresh}>
                    刷新
                </Button>

                <Table
                    // style={{ position: 'fixed' }}
                    columns={columns}
                    dataSource={this.state.userList}
                    bordered
                    pagination={{ pageSize: 4 }}
                    scroll={{ y: 280 }}
                />
            </div>
        );
    }
}

export default listTab;
